import PagePromoterUtil, { PagePromoter } from '../../../data/common/pagePromoter';
import AppSceneUtil, { PageScene } from '../../../data/common/appScene';
import SessionUtil, { JxbHttpClient } from "../../../data/session/session"
import SystemUtil from '../../../shell/system/system';
import { CommonBizLogicError, NeedToSwitchServerError } from '../../../utils/network';
import InteractionUtil from '../../../shell/ui/interaction';
import SessionUserUtil from '../../../data/session/sessionUser.js';
import SessionSellingServerUtil from '../../../data/session/sessionSellingServer';
import PageUtil from '../../../shell/router/page';
const Common = require('../../../utils/common.js');

Page({
  data: {
    token: '',
    itemId: '',
    itemInfo: {},
    carNumber: 1,
    gross: 0.00,
    indicatorDots: true,
    autoplay: false,
    interval: 3000,
    duration: 500,
    detail: {},
    seckills: true,
    seckill: {},
    limits: false,
    limit: {},
    imageSize: [],
    isShowShoppingchart: false,
    productsList: {},
    productMaskClass: "",
    isShowChartChange: false,
    show_pop: true,
    alert: false,
    isShare: false,
    imgHeight: 0,
    promiseDelivery: {},
    navIndex: 0,
    categorys:[],
    isMember:false,
    cardMsg: {},//客服卡片信息
  },
  onLoad: function (options) {
    SessionUserUtil.renewCache().then(() => {
      const user = SessionUserUtil.getInstanceSync()._data
      const {sale_type} = user
      this.setData({
        isMember: sale_type * 1 === 3
      })
    })
    getApp().getSaleMode()
    // 开启转发按钮
    PagePromoterUtil.showShareMenu(true).then()
    SessionUtil.getInstance().then(session => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this)
      let page = this, sessionUser = session.getTheSessionUserSync()
      wx.removeStorageSync('checkedlis');
      let dataToSet = {};
      dataToSet.userid = sessionUser.userId;
      if (options.itemId) {
        dataToSet.itemId = options.itemId;
      }
      let pageScene = new PageScene(this)
      if (pageScene.hasPromoter()) { // 分享过来
        dataToSet.isShare = true;
      }
      this.setData(dataToSet)
      wx.setNavigationBarTitle({
        title: '商品详情'
      })
      wx.showLoading({
        title: '数据加载中',
      })
      InteractionUtil.showLoading(200);
      Promise.all([
        this.getItemYearList(),
        this.itemInfo(),
        this.refreshCartDetail(), // 
        this.queryPromiseDelivery(options.itemId) //承诺达
      ]).then(()=>{
        InteractionUtil.hideLoading();
      })
      /**获取屏幕宽度 */
      this.setData({
        w_width: SystemUtil.getSystemInfo(false).windowWidth
      })
      wx.setStorageSync("if_refresh", 4);
    })
  },

  onShow: function () {
    getApp().getSaleMode()
    SessionUtil.getInstance().then(session => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this, false)
      // 更新购物车
      this.refreshCartDetail();
    })
  },

  // 获取这款酒的年份
  getItemYearList: function () {
    var page = this;
    var itemId = page.data.itemId;
    InteractionUtil.showLoading(300)
    JxbHttpClient.getClient().get({
      url: '/AppMaster/Item/getItemYearsList',
      data: {
        item_id: itemId
      }
    }).then(jxbResp=>{
      InteractionUtil.hideLoading()
      var list = jxbResp.data.item_year_list;
      if (list.length > 0) {
        this.setData({
          list_year: list
        })
      }
    }).catch(err=>{
      console.log(err);
      InteractionUtil.hideLoading()
      InteractionUtil.showNotice(err.message)
    })
  },
  // 点击年份切换商品
  changeYear: function (e) {
    var dataToSet = {
      choosed: 0
    };
    var id = e.currentTarget.id;
    var products = this.data.productsList.productsList;
    dataToSet.itemId = id;
    this.setData(dataToSet);
    this.itemInfo().then(()=>{
      for (var i = 0; i < products.length; i++) {
        if (products[i].itemid == id) {
          dataToSet.choosed = products[i].carNumber;
          break;
        }
      }
      this.setData(dataToSet);
    })
    
  },
  itemInfo: function (action = '') {
    // 加载详情
    var page = this;
    var itemId = page.data.itemId;
    InteractionUtil.showLoading(300)
    return JxbHttpClient.getClient().get({
      url: '/AppMaster/Item/itemDetail',
      data: {
        itemId: itemId
      },
    }).then(jxbResp => {
      if(jxbResp.errorCode===303){
        throw new NeedToSwitchServerError(jxbResp.message, jxbResp.errorCode, jxbResp)
      }
      if(!jxbResp.data){
        throw new CommonBizLogicError(jxbResp.message, 100, jxbResponse)
      }
      InteractionUtil.hideLoading()
      var respData = jxbResp.data;
      console.log(jxbResp,jxbResp.data, jxbResp.detail??"");
      var detailRaw = respData.detail??"";
      var imgReg = /(http.*?\.(jpg|jpeg|gif|png|webp))/ig;
      var imgRegResult = detailRaw.match(imgReg);
      var catAttr = respData.categoryAttribute
      var dateToSet = {
        categorys: catAttr
      }
      if (respData.productName) {
        dateToSet.cardMsg = {
          imgUrl: imgRegResult && imgRegResult[0] || respData.mediasList[0]['img_uri'],
          itemId:respData.itemId,
          productName: respData.productName
        };
      }
      this.setData(dateToSet);
      if (respData.activity_list.length > 0) {
        var activList = respData.activity_list
        for (var i = 0; i < activList.length; i++) {
          if (activList[i].activity_category == 6) {
            dateToSet.seckill = activList[i];
            dateToSet.seckills = false;
            var secondToEnd = activList[i].activity_end_second;
            var b = setInterval(function () {
              secondToEnd--
              if (secondToEnd >= 0) {
                page.setData({
                  endDate: page.ShowCountDown(secondToEnd),
                });
              } else {
                clearTimeout(b);
                // 刷新详情信息
                page.itemInfo()
              }
            }, 1000);
          } else if (activList[i].activity_category == 4) {
            page.setData({
              limit: activList[i],
              limits: true,
            });
          }
        }
      } else {
        page.setData({
          seckills: true,
        });
      }
      const { mediasList } = respData
      const item = mediasList && mediasList[0]
      const { img_uri } = item
      wx.getImageInfo({
        src: img_uri,
        success: res => {
          const { height, width } = res
          let windowWidth = SystemUtil.getSystemInfo(false).windowWidth
          page.setData({
            itemInfo: respData,
            detail: imgRegResult ? imgRegResult : respData.mediasList.map(item => item.img_uri),
            imgHeight: windowWidth / width * height
          });
        }
      })
    }).catch(err=>{
      InteractionUtil.hideLoading()
      console.log(err);
      if(!(err instanceof Error)){
        return;
      }
      if(err.jxbResponse && err.jxbResponse.errorCode === 303){
        // 业务重定向（切换销售模式、顾问、店铺等）
        let {action, target, tips} = err.jxbResponse.data
        console.log(err.jxbResponse.data, 'action');
        // 在主流程中获取页面信息，否则可能会出现“当前页面”与getCurrentPages().pop()获取的不一致的问题
        let curPage = PageUtil.getHistory(-1),
        accessUri = PageUtil.getUri(curPage);
        console.log('referer', curPage, accessUri, this, this.options);
        switch(action){
          case "switch_sales_model":
            // 切换销售类型，1=零售，2=批发
            console.log('切换销售类型')
            InteractionUtil.showAlert(tips).then(()=>{
              SessionSellingServerUtil.switchSalesModel(target).then(()=>{
                // 重新加载当前页面
                wx.redirectTo({
                  url: "/"+accessUri,
                  fail: err => console.log(err),
                });
              })
            })
            break;
          case "apply_sales_model":
            // 申请开通指定的销售类型，1=零售，2=批发  
            console.log('申请开通指定的销售类型')
            InteractionUtil.showConfirm(tips, '暂无权限').then(optResult=>{
                if(optResult.confirm=== true){
                  wx.redirectTo({
                    url: '/subPage/wholesale/index?type=3',
                  })
                }else{
                  InteractionUtil.showNotice('即将返回首页...')
                  wx.switchTab({
                    url: '/pages/index/index',
                    fail: err => {console.log(err)},
                  });
                   
                }
            })
            break;
          case "switch_selling_server":
            // 切换顾问
            console.log('切换顾问')
            InteractionUtil.showAlert(tips).then(()=>{
              SessionSellingServerUtil.switchSellingServer(target.salesman_id).then(()=>{
                return Promise.all([SessionSellingServerUtil.renewCache(), SessionUserUtil.renewCache()])
              }).then(()=>{
                getApp().getSaleMode();
                // 重新加载当前页面
                wx.redirectTo({
                  url: "/"+accessUri,
                  fail: err => console.log(err),
                });
              })
            })
            
            break;
          case "switch_shop":
            // 切换门店
            console.log('切换门店')
            InteractionUtil.showAlert(tips).then(()=>{
              SessionSellingServerUtil.switchUnionStore(target.agent_id, target.salesman_team_id).then(jxbResp=>{
                getApp().getSaleMode();
                // 修改 storage中的position.store的信息
                console.log('切换门店 switch_shop')
                // 重新加载当前页面
                wx.redirectTo({
                  url: "/"+accessUri,
                  fail: err => console.log(err),
                });
                  
              })
            })
            break;
          default:
            console.log('未知的操作')
            InteractionUtil.showNotice(`${tips}[${target}]`)
        }
        let salesType = SessionUserUtil.getInstanceSync()._data.sale_type; // 1=零售，2=批发， 3=会员
        
      }else{
        InteractionUtil.showAlert(err.message, '出错了！').then(()=>{
          var pagesStack = getCurrentPages();
          if (pagesStack.length > 2) {
            wx.navigateBack()
          } else {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        })
      }
    })
  },
  ShowCountDown: function (endDate) {
    //倒计时
    var leftsecond = parseInt(endDate);
    //var day1=parseInt(leftsecond/(24*60*60*6)); 
    var day1 = Math.floor(leftsecond / (60 * 60 * 24));
    var hour = Math.floor((leftsecond) / 3600) + '';
    var hour1 = Math.floor((leftsecond - day1 * 24 * 60 * 60) / 3600);
    var minute = Math.floor((leftsecond - day1 * 24 * 60 * 60 - hour1 * 3600) / 60) + '';
    var second = Math.floor(leftsecond - day1 * 24 * 60 * 60 - hour1 * 3600 - minute * 60) + '';
    var divname = {};
    divname.hour = hour.length < 2 ? ('0' + hour) : hour;
    divname.minute = minute.length < 2 ? ('0' + minute) : minute;
    divname.second = second.length < 2 ? ('0' + second) : second;
    return divname;
  },
  onPullDownRefresh: function () {
    // 下拉刷新
    this.itemInfo().then(()=>{
      wx.stopPullDownRefresh();
    })
  },
  imageLoad: function (e) {

    var index = e.currentTarget.id;;
    var page = this;
    var imageHeight = page.data.imageSize;
    imageHeight[index] = Common.imageLoadAn(e, (page.data.w_width - 20)).toFixed(2);
    page.setData({
      imageSize: imageHeight
    })
  },
  onShareAppMessage: function () {
    // 构造并返回自定义数据
    return (new PagePromoter(this.route, { itemId: this.data.itemId }))
      .setShareTitle(this.data.itemInfo.productName)
      .buildShareInfo()
  },
  // 显示数量修改面板
  show_count: function () {
    // if (!this.productNums()) {
    //   return false;
    // }
    var page = this;
    page.setData({
      show_pop: !page.data.show_pop
    })
  },
  AddCart: function (e) {
    var page = this;
    var ID = e.currentTarget.id
    console.log(e)
    var itemId = ID.split('-')[0];
    var stock = ID.split('-')[1];
    if (stock == 0) {
      InteractionUtil.showNotice('库存不足！')
    } else {
      InteractionUtil.showLoading(300);
      JxbHttpClient.getClient().post({
        url: '/AppMaster/PosCart/PosAddCart',
        data: {
          number: 1,
          itemId: itemId
        },
      }).then(jxbResp=>{
        InteractionUtil.hideLoading();
        InteractionUtil.showSuccess('添加成功');
        this.refreshCartDetail();
      }).catch(err=>{
        InteractionUtil.hideLoading();
        InteractionUtil.showNotice('添加失败：'+err.message)
      })
    }
  },
  // 查看优惠券
  coupon: function () {
    var page = this,
      coupon_json = {},
      coupon_array = [],
      detail = page.data.itemInfo;
    coupon_json.item_id = detail.itemId;
    coupon_json.count = page.data.choosed;
    coupon_json.price = detail.promotePrice;

    coupon_array.push(coupon_json);
    coupon_array = JSON.stringify(coupon_array);
    var userid = wx.getStorageSync('user_id');
    if (userid < 0) {
      wx.navigateTo({
        url: '/pages/my/logintype/logintype?from=1&coupon_array=' + coupon_array
      });
    } else {
      wx.navigateTo({
        url: '/pages/coupon/use/use?coupon_array=' + coupon_array + '&is_useCoupon=showAllCoupon'
      })
    }

  },

  numberReduce: function () {
    var page = this;
    var cnumber = page.data.carNumber;
    cnumber--;
    if (cnumber >= 1) {
      page.setData({
        carNumber: cnumber
      })
    }
  },
  purchase: function () {
    if (!this.productNums()) {
      return false;
    }
    var userid = this.data.userid;
    if (userid < 0) {
      wx.navigateTo({
        url: '/pages/my/logintype/logintype?from=0&checkedlis=' + this.data.itemId
      });
    } else {
      InteractionUtil.showLoading(300);
      JxbHttpClient.getClient().get({
        url: '/AppMaster/PosCart/PosAddCart',
        data: {
          number: 1,
          itemId: this.data.itemId
        }
      }).then(jxbResp=>{
        InteractionUtil.hideLoading()
        wx.navigateTo({
          url: '/pages/product/orderConfirm/index?checkedlis=' + this.data.itemId
        });
        this.refreshCartDetail();
      }).catch(err=>{
        InteractionUtil.hideLoading()
        InteractionUtil.showNotice(err.message);
      })
    }
  },
  clearStorageSync: function () {
    wx.setStorageSync("dilivery", '');
    wx.setStorageSync("invoice", {});
    wx.setStorageSync("pay", {});
  },
  refreshCartDetail: function () {
    this.setData({
      choosed: 0,
    });
    return JxbHttpClient.getClient().get('/AppMaster/PosCart/cartDetail').then(jxbResp => {
      let respData = jxbResp.data, products = respData.productsList, list = respData.activity_list
      let total = 0, gross = 0.00, itemids = [], limits = [];
      for (let z = 0; z < list.length; z++) {
        if (list[z].activity_category == 6) {
          itemids = itemids.concat(list[z].itemids);
        }
        if (list[z].activity_category == 4) {
          limits = limits.concat(list[z].itemids);
        }
      }
      for (let i = 0; i < products.length; i++) {
        total = total + products[i].carNumber;
        gross = gross + products[i].carNumber * products[i].show_price;
        if (products[i].itemid == this.data.itemId) {
          // carNumber: products[i].carNumber,
          this.setData({
            carNumber: 1,
            choosed: products[i].carNumber,
            cartId: products[i].cartId,
          });
        }
        let z = Common.contains(itemids, products[i].itemid),
          w = Common.contains(limits, products[i].itemid);
        if (z && w) {
          products[i].activity_list = ['秒杀', '限购']
        } else {
          if (z) {
            products[i].activity_list = ['秒杀'];
          }
          if (w) {
            products[i].activity_list = ['限购'];
          }
        }
      }
      respData.total = total;
      respData.gross = gross.toFixed(2);
      respData.productsList = products;
      this.setData({
        productsList: respData
      })
    }).catch(err => {
      console.log(err)
      this.setData({
        productsList: {},
        carNumber: 1,
      })
      InteractionUtil.showNotice(err.message)
    })
  },
  shoppingChartList: function () {
    var page = this;
    var isShowShoppingchart = page.data.isShowShoppingchart;
    var bIsShowShoppingchart = isShowShoppingchart ? false : true;
    page.setData({
      isShowShoppingchart: bIsShowShoppingchart,
      productMaskClass: bIsShowShoppingchart ? "product-mask" : ""
    })
  },
  // 输入框失焦置0
  resetTozero: function (e) {
    this.setData({
      carNumber: e.detail.value == "" ? 0 : e.detail.value
    })
  },
  /**
   *  更新数量
   */
  updateInput: function (e) {
    this.setData({
      carNumber: e.detail.value
    })
  },
  // 输入框数量加一
  numberAdd: function (e) {
    var page = this;
    var cnumber = page.data.carNumber;
    cnumber++;
    if (cnumber >= 0) {
      page.setData({
        carNumber: cnumber
      })
    }
  },
  shoppingCartAdd: function (e) {
    var page = this;
    var d = e.currentTarget.id;
    var itemId = d.split('_')[0];
    var fromData = d.split('_')[1];
    if (!this.productNums()) {
      return false;
    }
    if (fromData == 1) {
      var number = page.data.carNumber;
    } else {
      var number = 1;
    }
    InteractionUtil.showLoading(300);
    JxbHttpClient.getClient().post({
      url: '/AppMaster/PosCart/PosAddCart',
      data: {
        number: number,
        itemId: itemId
      }
    }).then(jxbResp=>{
      InteractionUtil.hideLoading()
      InteractionUtil.showSuccess('添加成功');
      this.refreshCartDetail()
      this.setData({
        show_pop: true,
        alert: true
      })
    }).catch(err=>{
      InteractionUtil.hideLoading()
      InteractionUtil.showNotice(err.message)
    })
  },

  goCarts: function () {
    wx.switchTab({
      url: '/pages/shoppingcart/index'
    })
  },
  toIndex() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  productNums: function () {
    var a = false;
    if (this.data.itemInfo.productNums < 1) {
      InteractionUtil.showNotice('库存不足！');
    } else {
      a = true;
    }
    return a;
  },
  changePlay(e) {
    const { detail } = e
    this.setData({
      indicatorDots: detail
    })
  },
  queryPromiseDelivery(id) {
    JxbHttpClient.getClient().get({
      url: '/AppMaster/AgentUnion/getShippingSpeedMessage',
      data: { item_id: id }
    }).then(_ => {
      const { data } = _
      const storage = wx.getStorageSync('position')
      const { store } = storage
      this.setData({
        promiseDelivery: data
      })
    })
  },
  chooseAddress() {
    wx.navigateTo({
      url: '/subPage/modifyAddress/index',
    })
  },
  //点击客服卡片跳转详情页
  contactHandle(e){
    var path = e.detail.path, query = e.detail.query, params = '';
    if (path) {
        for (var key in query) {
            params += key + '=' + query[key] + '&';
        }
        params = params.slice(0, params.length - 1);
        wx.navigateTo({
            url: path + '?' + params
        })
    }
  },
  changeNav(e){
   const {dataset} = e.currentTarget
   const {index} = dataset
   this.setData({
     navIndex: index*1
   })
  }
})